package com.google.code.dnaep.jdo;

import org.datanucleus.jdo.JDOExtent;
import org.datanucleus.jdo.JDOQuery;

import com.google.appengine.api.datastore.Key;
import com.google.code.dnaep.EntityKindHelper;

public class PersistenceManager extends org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManager {

	public PersistenceManager(org.datanucleus.jdo.JDOPersistenceManagerFactory apmf, String userName, String password) {
		super(apmf, userName, password);
	}

	@Override
	public Object getObjectById(Class cls, Object key) {
		if (key instanceof Key) {
			Key geaKey = (Key) key;
			cls = EntityKindHelper.getKindClass(geaKey.getKind());
		} else if (cls == null) {
			throw new IllegalArgumentException("cls may only be null if key is of type com.google.appengine.api.datastore.Key");
		}

		return super.getObjectById(cls, key);
	}

	@Override
	public synchronized javax.jdo.Query newQuery(String language, Object query) {
		JDOQuery jdoQuery = (JDOQuery) super.newQuery(language, query);
		return new Query(jdoQuery);
	}

	@Override
    public synchronized javax.jdo.Extent getExtent(Class pcClass, boolean subclasses) {
		JDOExtent jdoExtent = (JDOExtent) super.getExtent(pcClass, subclasses);
	    return new Extent(jdoExtent, subclasses);
    }

}
